#!/usr/bin/env python3
# -*- coding: utf_8 -*-

import sys
import os
import re
import traceback


def dynimp(dirs, verbose=False, pat=None):
    pat = pat or r"\bif_.+\.py\b"
    regex = re.compile(pat)

    def load(fname):
        if not regex.match(fname):
            return

        name, ext = os.path.splitext(fname)
        try:
            __import__(name)
            if verbose:
                print("OK: Import %s" % fname)
        except:
            if verbose:
                print("NG: Import %s" % fname)
                traceback.print_exc()

    for rootDir in dirs:
        sys.path.append(rootDir)
        for _, _, files in os.walk(rootDir, topdown=True):
            for fname in files:
                load(fname)
            # Only process the topmost files int rootDir
            break


def dynscan(*dirs):
    modDirs = []

    for rootDir in dirs:
        for root, dirs, files in os.walk(rootDir, topdown=True):
            if "__dynskip__" in files or "__dynmodu__" not in files:
                continue
            modDirs.append(root)

    return modDirs
